import React, { ReactElement, useReducer, Reducer, useContext } from 'react';
import { AppStore } from '../../reducer';
import FetchFailed from '../FetchFailed';

interface Provider {
  reducer: any;
  initialState: any;
  Store: any;
  actions: any;
  reload?: any;
  children?: any;
}

export default ({
  reducer,
  initialState,
  Store,
  actions,
  reload,
  children,
  ...props
}: Provider): ReactElement => {
  const [state, dispatch] = useReducer<Reducer<any, any>>(
    reducer,
    initialState
  );

  const { isFetchFailed = false } = state;

  const { appState } = useContext(AppStore);
  actions(dispatch, state, appState);

  return (
    <Store.Provider value={{ state, dispatch }} {...props}>
      {isFetchFailed ? <FetchFailed onReload={reload} /> : children}
    </Store.Provider>
  );
};
